<?php

namespace app\modules\setting\models;

use Yii;

/**
 * This is the model class for table "rbac_role_permissions".
 *
 * @property int $role_permission_id
 * @property int $role_id
 * @property int $permission_id
 * @property string $crt_name
 * @property string $crt_time
 */
class RolePermissions extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'rbac_role_permissions';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['role_id', 'permission_id', 'crt_time'], 'required'],
            [['role_id', 'permission_id'], 'integer'],
            [['crt_time'], 'safe'],
            [['crt_name'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'role_permission_id' => 'Role Permission ID',
            'role_id' => 'Role ID',
            'permission_id' => '权限',
            'crt_name' => 'Crt Name',
            'crt_time' => 'Crt Time',
        ];
    }


    /**
     * @param $role_id
     * @param $permission_ids
     *
     * @return bool
     * @throws \yii\db\Exception
     * @author sally
     * @date   2020-07-06
     */
    static public function saveRolePermissions($role_id, $permission_ids)
    {
        // set old permissions to delete
        RolePermissions::updateAll(['delete_at' => strtotime(date("Y-m-d H:i:s"))], ['role_id' => $role_id, 'delete_at' => 0]);

        $insert_data = [];
        $crt_name = Yii::$app->user->identity->username;
        $crs_time = date('Y-m-d H:i:s');
        foreach ($permission_ids as $permission_id) {
            $insert_data[] = [$role_id, $permission_id, $crt_name, $crs_time];
        }


        // add new roles
        Yii::$app->db->createCommand()->batchInsert('rbac_role_permissions', ['role_id', 'permission_id', 'crt_name', 'crt_time'], $insert_data)->execute();

        return true;
    }
}
